"""
Embed routes for LandPPT - 嵌入式页面路由
"""

import logging
import time
from typing import Optional
from fastapi import APIRouter, Request, Depends, HTTPException, Response
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session

from supertokens_python.recipe.session.framework.fastapi import verify_session
from supertokens_python.recipe.session.interfaces import SessionContainer

from ..auth.middleware import get_current_user_optional, get_current_user_required
from ..database.database import get_db
from ..database.models import User
from ..core.config import app_config

logger = logging.getLogger(__name__)

router = APIRouter()
templates = Jinja2Templates(directory="src/landppt/web/templates")

# Helper function to create context processor for templates
def get_template_context(request: Request):
    """Get additional template context including url_for function"""
    root_path = request.scope.get("root_path", "")
    
    def url_for(path: str):
        """Generate URL with proper root_path prefix"""
        if not path.startswith("/"):
            path = f"/{path}"
        if root_path and not path.startswith(root_path):
            return f"{root_path}{path}"
        return path
    
    return {"url_for": url_for, "root_path": root_path}

def render_embed_template(template_name: str, request: Request, context: dict = None):
    """Helper function to render embed template with proper context and security headers"""
    if context is None:
        context = {}
    
    # Always include request
    context["request"] = request
    
    # Add template context (url_for, root_path, etc.)
    context.update(get_template_context(request))
    
    # Create response with template
    response = templates.TemplateResponse(template_name, context)
    
    # Set security headers for embedding
    response.headers["Content-Security-Policy"] = "frame-ancestors https://yunzhishi.zzz4ai.com"
    response.headers.pop("X-Frame-Options", None)  # Remove X-Frame-Options if present
    
    return response

def log_embed_operation(
    batch_id: str,
    project_id: str,
    user_id: Optional[str],
    operation: str,
    status: str,
    error_reason: Optional[str] = None,
    extra_data: Optional[dict] = None
):
    """记录嵌入操作日志"""
    log_data = {
        "batch_id": batch_id,
        "project_id": project_id,
        "user_id": user_id,
        "operation": operation,
        "status": status,
        "timestamp": time.time(),
        "error_reason": error_reason,
        "extra_data": extra_data or {}
    }
    
    logger.info(f"Embed operation: {log_data}")


@router.get("/ppt/embed/projects/{project_id}", response_class=HTMLResponse)
async def embed_project(
    request: Request,
    project_id: str,
    batch_id: str,
    db: Session = Depends(get_db)
):
    """嵌入式项目页面入口"""
    try:
        # 验证 Supertokens Session
        user = get_current_user_optional(request, db)
        
        if not user:
            # 没有有效 session，返回未授权页面
            log_embed_operation(
                batch_id=batch_id,
                project_id=project_id,
                user_id=None,
                operation="embed_access",
                status="unauthorized"
            )
            
            return render_embed_template("embed_unauthorized.html", request, {
                "project_id": project_id,
                "batch_id": batch_id,
                "message": "需要登录才能访问此项目"
            })
        
        # TODO: 这里可以添加项目权限检查逻辑
        # 例如检查用户是否有权限访问指定的 project_id
        
        # 记录成功访问日志
        log_embed_operation(
            batch_id=batch_id,
            project_id=project_id,
            user_id=str(user.id),
            operation="embed_access",
            status="success"
        )
        
        return render_embed_template("embed_project.html", request, {
            "project_id": project_id,
            "batch_id": batch_id,
            "user": user.to_dict(),
            "api_domain": app_config.supertokens_api_domain
        })
        
    except Exception as e:
        logger.error(f"Embed project error: {e}")
        
        log_embed_operation(
            batch_id=batch_id,
            project_id=project_id,
            user_id=None,
            operation="embed_access",
            status="error",
            error_reason=str(e)
        )
        
        return render_embed_template("embed_error.html", request, {
            "project_id": project_id,
            "batch_id": batch_id,
            "error": "系统错误，请稍后重试"
        })


@router.post("/api/embed/projects/{project_id}/status")
async def update_embed_status(
    request: Request,
    project_id: str,
    batch_id: str,
    status: str,
    progress: Optional[int] = None,
    stage: Optional[str] = None,
    db: Session = Depends(get_db),
    user: User = Depends(get_current_user_required)
):
    """更新嵌入项目状态（供内部调用）"""
    try:
        # 记录状态更新
        log_embed_operation(
            batch_id=batch_id,
            project_id=project_id,
            user_id=str(user.id),
            operation="status_update",
            status=status,
            extra_data={
                "progress": progress,
                "stage": stage
            }
        )
        
        return {
            "success": True,
            "batch_id": batch_id,
            "project_id": project_id,
            "status": status
        }
        
    except Exception as e:
        logger.error(f"Update embed status error: {e}")
        raise HTTPException(status_code=500, detail="状态更新失败")


@router.post("/api/embed/projects/{project_id}/success")
async def embed_project_success(
    request: Request,
    project_id: str,
    batch_id: str,
    preview_url: str,
    token_stats: Optional[dict] = None,
    db: Session = Depends(get_db),
    user: User = Depends(get_current_user_required)
):
    """标记嵌入项目生成成功"""
    try:
        # 记录成功日志
        log_embed_operation(
            batch_id=batch_id,
            project_id=project_id,
            user_id=str(user.id),
            operation="generation_success",
            status="success",
            extra_data={
                "preview_url": preview_url,
                "token_stats": token_stats
            }
        )
        
        return {
            "success": True,
            "batch_id": batch_id,
            "project_id": project_id,
            "preview_url": preview_url,
            "token_stats": token_stats
        }
        
    except Exception as e:
        logger.error(f"Embed project success error: {e}")
        raise HTTPException(status_code=500, detail="操作失败")


@router.post("/api/embed/projects/{project_id}/fail")
async def embed_project_fail(
    request: Request,
    project_id: str,
    batch_id: str,
    reason: str,
    db: Session = Depends(get_db),
    user: User = Depends(get_current_user_required)
):
    """标记嵌入项目生成失败"""
    try:
        # 记录失败日志
        log_embed_operation(
            batch_id=batch_id,
            project_id=project_id,
            user_id=str(user.id),
            operation="generation_fail",
            status="failed",
            error_reason=reason
        )
        
        return {
            "success": True,
            "batch_id": batch_id,
            "project_id": project_id,
            "reason": reason
        }
        
    except Exception as e:
        logger.error(f"Embed project fail error: {e}")
        raise HTTPException(status_code=500, detail="操作失败")


@router.get("/api/embed/projects/{project_id}/download")
async def embed_project_download(
    request: Request,
    project_id: str,
    db: Session = Depends(get_db),
    user: User = Depends(get_current_user_required)
):
    """嵌入项目下载接口（需要 session 验证）"""
    try:
        # TODO: 实现实际的下载逻辑
        # 这里应该检查用户是否有权限下载该项目
        
        # 记录下载日志
        log_embed_operation(
            batch_id="download",
            project_id=project_id,
            user_id=str(user.id),
            operation="download",
            status="success"
        )
        
        # 返回下载链接或文件
        return {
            "success": True,
            "project_id": project_id,
            "download_url": f"/api/projects/{project_id}/download"
        }
        
    except Exception as e:
        logger.error(f"Embed project download error: {e}")
        raise HTTPException(status_code=500, detail="下载失败")
